package com.iwhalecloud.bss.kite.cucc.service.batch.attr.processor;

import java.util.List;
import java.util.Objects;

import org.springframework.stereotype.Component;

import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.constant.SymbolConsts;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.api.attr.IUnicomRegionService;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegion;
import com.iwhalecloud.bss.kite.cucc.client.dto.attr.UnicomRegionQry;
import com.iwhalecloud.bss.kite.cucc.common.util.KiteAssert;
import com.iwhalecloud.bss.kite.cucc.service.batch.attr.BatchAttrProcessor;
import com.iwhalecloud.bss.kite.cucc.service.batch.attr.BatchAttrUtil;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.dto.KiteAttrDTO;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.exception.BssException;

import lombok.RequiredArgsConstructor;

/**
 * @author : xie.zhengjun
 * @className : InstallAddressProcessor
 * @description : 批量受理装机地址Z端属性处理器
 *      SDH:10002174、60000016、60000015、60000014
 *      光纤：60000055
 *      以太网：60000179、60000178、60000176、60000177
 * @date : 2021/6/10 17:27
 */
@Component
@BatchAttrProcessor(fieldName = { "2_0000107" }, prodId = {"10002385", "60000055", "60000179", "60000178", "60000176", "60000177",
    "60000017", "60000016", "60000015", "60000014", "10002230", "10002176", "10002384", "10002224", "10002387",
    "10002386", "10002187", "10002183", "10002174"
}) @RequiredArgsConstructor
public class ZInstallAddressProcessor implements IBatchAttrProcessor {
    private final IUnicomRegionService unicomRegionService;

    private final IOperateSceneInstService operateSceneInstService;

    private final IQuerySceneInstService querySceneInstService;

    @Override
    public void process(KiteAttrDTO attr, KiteInst inst, String sceneInstId, String custId) {
        String fieldName = attr.getFieldName();
        String value = attr.getValue();
        KiteAssert.notBlank(value, ErrorConsts.BUSI_COMMON_ERROR, "区域填写不合法！正确格式为：省/市/区");
        String[] fields = value.split(SymbolConsts.SLASH);
        KiteAssert.state(fields.length >= 3, ErrorConsts.BUSI_COMMON_ERROR, "区域填写不合法！正确格式为：省/市/区");

        String provinceName = fields[0];
        String cityName = fields[1];
        String districtName = fields[2];

        // 解析出省市县
        List<UnicomRegion> provinces = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry());
        UnicomRegion province = Objects.requireNonNull(provinces).stream()
            .filter(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionName(), provinceName)).findFirst()
            .orElseThrow(() -> new BssException("BatchAccept", ErrorConsts.BUSI_COMMON_ERROR.getCode(),
                "区域填写不合法！省份不存在"));
        String provinceCode = province.getRegionCode();

        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        // 跨域校验
        if (!KiteStringUtils.equals(provinceCode, kiteSceneInst.getProvinceNbr())) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("批量业务不允许受理跨域业务，请重新录入省市区信息！");
        }

        List<UnicomRegion> cities = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(provinceCode, "20"));
        UnicomRegion city = Objects.requireNonNull(cities).stream()
            .filter(unicomRegion -> KiteStringUtils.isEqual(unicomRegion.getRegionName(), cityName)).findFirst()
            .orElseThrow(() -> new BssException("BatchAccept", ErrorConsts.BUSI_COMMON_ERROR.getCode(),
                "区域填写不合法！市不存在"));
        String cityCode = city.getRegionCode();

        List<UnicomRegion> districts = unicomRegionService.subRegionFromPlatform(new UnicomRegionQry(cityCode, "30"));
        UnicomRegion district = Objects.requireNonNull(districts).stream()
            .filter(unicomRegion -> BatchAttrUtil.matchDistrict(districtName, unicomRegion.getRegionName())).findFirst()
            .orElseThrow(() -> new BssException("BatchAccept", ErrorConsts.BUSI_COMMON_ERROR.getCode(),
                "区域填写不合法！区不存在"));
        String districtCode = district.getRegionCode();

        String cityFieldName = "2_0000109";
        String districtFieldName = "2_0000111";

        // 设置省、市、县
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), fieldName, provinceCode, provinceName);
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), cityFieldName, cityCode, cityName);
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), districtFieldName, districtCode, districtName);

        // 标准地址ID的fieldName
        String addressIdFieldName = "200002619";
        // 装机地址第一段,即省市县 "2_0000105"
        String firstAddrFieldName = "2_0000105";
        // 装机地址第二段,即标准地址 "2_0000117"
        String lastAddrFieldName = "2_0000117";

        // 上传模板时，会将标准地址存入 装机地址的第一段，即省市县 "2_0000211"。此处取值重新设置
        String addressName = querySceneInstService.getProdInstAttrValue(custId, inst.getInstId(), firstAddrFieldName);

        // 互联网没有A/Z端,标准地址ID需要特殊处理
        if (KiteStringUtils.equals(ProdCateUtil.getSingleCateId(ProdCateUtil.DIA_CODE),
            CuccPosServiceUtils.getCateId(sceneInstId, custId))) {
            addressIdFieldName = "200002617";
        }

        if (KiteStringUtils.isEmpty(addressName)) {
            ErrorConsts.BUSI_COMMON_ERROR.throwOut("Z端装机地址不能为空");
        }

        // 设置装机地址的第一段，即省市县
        String firstAddr = KiteStringUtils.joinWith(SymbolConsts.COMMA, provinceCode, cityCode, districtCode);
        String firstAddrDesc = KiteStringUtils.joinWith(SymbolConsts.COMMA, provinceName, cityName, districtName);
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), firstAddrFieldName, firstAddr, firstAddrDesc);
        // 设置装机地址的第二段，即标准地址
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), lastAddrFieldName, addressName,
                addressName);

        /* 标准地址id可以为空
        // 根据标准地址查出标准地址id
        String addressId = BatchAttrUtil.getAddressId(inst, custId, lastAddrFieldName, addressName, provinceCode, cityCode, districtCode);
        // 设置标准地址id
        operateSceneInstService
            .setAttrValue(sceneInstId, inst.getInstType(), inst.getInstId(), addressIdFieldName, addressId, addressId);
         */
    }

}
